package com.example.asa;

import com.example.asa.DatabaseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/ReportDisasterServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50     // 50MB
)
public class ReportDisasterServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");

        if (user == null || !"resident".equals(session.getAttribute("role"))) {
            request.setAttribute("error", "您没有权限进行此操作");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        // 获取表单数据
        String eventType = request.getParameter("eventType");
        String address = request.getParameter("address");
        String status = request.getParameter("status");
        Part imagePart = request.getPart("image");

        // 非空校验
        if (eventType == null || eventType.isEmpty() ||
                address == null || address.isEmpty() ||
                status == null || status.isEmpty()) {
            request.setAttribute("error", "事件类型、地址、状态为必填项");
            request.getRequestDispatcher("reportDisaster.jsp").forward(request, response);
            return;
        }

        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = DatabaseUtil.getConnection();

            // 保存图片到服务器
            String imagePath = saveImage(imagePart);

            // 插入数据到数据库
            String sql = "INSERT INTO disasters2 (event_type, address, status, image_path, report_user) VALUES (?, ?, ?, ?, ?)";
            stmt = conn.prepareStatement(sql);

            stmt.setString(1, eventType);
            stmt.setString(2, address);
            stmt.setString(3, status);
            stmt.setString(4, imagePath);
            stmt.setString(5, user);

            int rowsInserted = stmt.executeUpdate();
            if (rowsInserted > 0) {
                response.sendRedirect("clviLianPage.jsp");
            } else {
                request.setAttribute("error", "灾情上报失败，请重试");
                request.getRequestDispatcher("reportDisaster.jsp").forward(request, response);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库错误：" + e.getMessage());
            request.getRequestDispatcher("reportDisaster.jsp").forward(request, response);
        } finally {
            try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {}
            try { if (conn != null) conn.close(); } catch (SQLException ignored) {}
        }
    }

    /**
     * 保存上传的图片到服务器指定目录，并返回相对路径
     */
    private String saveImage(Part imagePart) throws IOException {
        String fileName = imagePart.getSubmittedFileName();
        String uploadDir = "D:/gitt/cmd/target/asa-1.0-SNAPSHOT/images"; // 修改为您实际的目录
        String filePath = uploadDir + File.separator + fileName;

        File fileSaveDir = new File(uploadDir);
        if (!fileSaveDir.exists()) {
            boolean dirCreated = fileSaveDir.mkdirs();
            System.out.println("Directory created: " + dirCreated);
        }

        imagePart.write(filePath);
        return "images/" + fileName;
    }
}